﻿using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

namespace FlightService
{
    /// <summary>
    /// Web service for searching flights
    /// </summary>
    [WebService(Namespace = "http://sample.com/")]
    public class Service : System.Web.Services.WebService
    {
        /// <summary>
        /// Request from a client.
        /// </summary>
        Request request;

        /// <summary>
        /// Connection string to the database
        /// </summary>
        string cnnString
        {
            get { return ConfigurationManager.ConnectionStrings["FlightsConnectionString"].ToString(); }
        }

        /// <summary>
        /// Web service method for extracting the response from the server.
        /// </summary>
        /// <param name="flights">XML string in special format, containing requests for flights to be looked for</param>
        /// <returns>XML string in special format, containing details about found flights</returns>
        [WebMethod]
        public string GetFlights(string flights)
        {
            request = XmlParser.GetRequestOptionsFromXml(flights);
            request.Flights = XmlParser.XmlToFlights(flights);
            var filePath = Server.MapPath(@"~/App_Data/Flights.xls");

            var cnn = new SqlConnection(cnnString);
            cnn.Open();
            var response = string.Empty;
            switch (request.Option)
            {
                case "Default":
                    response = (new DefaultAlgorithm()).Execute(request, cnn);
                    break;
                case "Price":
                    response = (new PriceAlgorithm()).Execute(request, cnn);
                    break;
                case "Distance":
                    response = (new DistanceAlgorithm()).Execute(request, cnn);
                    break;
            }
            cnn.Close();

            return response;
        }
    }
}